package com.wlq.service.aop;

import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransactionContext;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author wlq
 * @date 2023/2/8
 * @descriptions 问题背景：下游服务降级处理 导致分布式回滚失败
 * 解决方案：AOP处理手动分布式事务回滚（上游服务也会自动回滚）
 */
@Aspect
@Component
public class GlobalTransExceptionAspect {

    private final static Logger logger = LoggerFactory.getLogger(GlobalTransExceptionAspect.class);


    @AfterThrowing(throwing = "e", pointcut = "execution(* com.wlq.service.service.*.*(..))")
    public void doRecoveryActions(Throwable e) throws TransactionException {
        if (!StringUtils.isBlank(RootContext.getXID()))
            logger.info("分布式事务方法执行异常:{}", e.getMessage());
        GlobalTransactionContext.reload(RootContext.getXID()).rollback();
    }

    /*@AfterReturning(value = "execution(* com.wlq.service.service.*.*(..))", returning = "result")
    public void afterReturning(JoinPoint point, Object result) throws TransactionException {
        if (!StringUtils.isBlank(RootContext.getXID())) {
            logger.info("分布式事务Id:{}", RootContext.getXID());
            GlobalTransactionContext.reload(RootContext.getXID()).commit();
        }
    }*/

}